package com.atguigu.gulimall.product.service.impl;

import com.atguigu.gulimall.common.to.SkuFullReductionOthersTo;
import com.atguigu.gulimall.common.to.SpuBoundsTo;
import com.atguigu.gulimall.common.utils.R;
import com.atguigu.gulimall.product.entity.*;
import com.atguigu.gulimall.product.feign.CouponFeignService;
import com.atguigu.gulimall.product.service.*;
import com.atguigu.gulimall.product.vo.Bounds;
import com.atguigu.gulimall.product.vo.Images;
import com.atguigu.gulimall.product.vo.Skus;
import com.atguigu.gulimall.product.vo.SpuSaveVo;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.atguigu.gulimall.common.utils.PageUtils;
import com.atguigu.gulimall.common.utils.Query;

import com.atguigu.gulimall.product.dao.SpuInfoDao;
import org.springframework.transaction.annotation.Transactional;


@Service("spuInfoService")
public class SpuInfoServiceImpl extends ServiceImpl<SpuInfoDao, SpuInfoEntity> implements SpuInfoService {

    @Autowired
    private SpuImagesService spuImagesService;

    @Autowired
    private SpuInfoDescService spuInfoDescService;

    @Autowired
    private AttrService attrService;

    @Autowired
    private ProductAttrValueService productAttrValueService;

    @Autowired
    private SkuInfoService skuInfoService;

    @Autowired
    private SkuImagesService skuImagesService;

    @Autowired
    private SkuSaleAttrValueService skuSaleAttrValueService;

    @Autowired
    private CouponFeignService couponFeignService;


    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<SpuInfoEntity> page = this.page(
                new Query<SpuInfoEntity>().getPage(params),
                new QueryWrapper<SpuInfoEntity>()
        );

        return new PageUtils(page);
    }

    /**
     * 保存Spu信息
     *
     * @param spuSaveVo
     */
    @Transactional
    @Override
    public void saveSpuInfo(SpuSaveVo spuSaveVo) {
        SpuInfoEntity spuInfoEntity = new SpuInfoEntity();
        // Spu信息
        // 1. spu基本信息 pms_spu_info
        BeanUtils.copyProperties(spuSaveVo, spuInfoEntity);
        spuInfoEntity.setCreateTime(new Date());
        spuInfoEntity.setUpdateTime(new Date());
        // 保存Spu基本信息的方法
        this.save(spuInfoEntity);

        // 2. spu的图片信息  pms_spu_images
        List<SpuImagesEntity> spuImagesEntities = spuSaveVo.getImages().stream().map((img) -> {
            SpuImagesEntity spuImagesEntity = new SpuImagesEntity();
            spuImagesEntity.setSpuId(spuInfoEntity.getId());
            spuImagesEntity.setImgUrl(img);
            return spuImagesEntity;
        }).filter((item) -> {
            return StringUtils.isNotEmpty(item.getImgUrl());
        }).collect(Collectors.toList());
        // 保存图片基本信息
        spuImagesService.saveImages(spuImagesEntities);

        // 3. spu的描述信息   pms_spu_info_desc
        List<String> decript = spuSaveVo.getDecript();
        SpuInfoDescEntity spuInfoDescEntity = new SpuInfoDescEntity();
        spuInfoDescEntity.setSpuId(spuInfoEntity.getId());
        spuInfoDescEntity.setDecript(String.join(",", decript));
        spuInfoDescService.saveDescription(spuInfoDescEntity);
        // 4. spu的规格属性信息  pms_product_attr_value
        List<ProductAttrValueEntity> productAttrValueEntityList = spuSaveVo.getBaseAttrs().stream().map((item) -> {
            ProductAttrValueEntity productAttrValueEntity = new ProductAttrValueEntity();
            BeanUtils.copyProperties(item, productAttrValueEntity);
            AttrEntity attrEntity = attrService.getById(item.getAttrId());
            productAttrValueEntity.setAttrName(attrEntity.getAttrName());
            productAttrValueEntity.setAttrSort(0);
            productAttrValueEntity.setQuickShow(item.getShowDesc());
            productAttrValueEntity.setSpuId(spuInfoEntity.getId());
            return productAttrValueEntity;
        }).collect(Collectors.toList());
        // 保存规格属性信息
        productAttrValueService.saveProductAttrValues(productAttrValueEntityList);
        // 5. spu的积分信息 sms_spu_bounds
        SpuBoundsTo spuBoundsTo = new SpuBoundsTo();
        Bounds bounds = spuSaveVo.getBounds();
        BeanUtils.copyProperties(bounds, spuBoundsTo);
        spuBoundsTo.setSpuId(spuInfoEntity.getId());
        R r = couponFeignService.save(spuBoundsTo);
        if (r.getCode() != 0) {
            log.error("远程调用优惠券服务失败");
        }
        // Sku信息
        // 1.sku的基本信息 pms_sku_info
        List<Skus> skus = spuSaveVo.getSkus();
        if (skus != null && skus.size() > 0) {
            skus.stream().forEach((sku) -> {
                String defaultImg = "";
                // 获取默认图片
                for (Images image : sku.getImages()) {
                    if (image.getDefaultImg() == 1) {
                        defaultImg = image.getImgUrl();
                    }
                }
                SkuInfoEntity skuInfoEntity = new SkuInfoEntity();
                BeanUtils.copyProperties(sku, skuInfoEntity);
                skuInfoEntity.setSpuId(spuInfoEntity.getId());
                skuInfoEntity.setBrandId(spuInfoEntity.getBrandId());
                skuInfoEntity.setCatalogId(spuInfoEntity.getCatalogId());
                // 设置默认图片地址
                skuInfoEntity.setSkuDefaultImg(defaultImg);
                // 保存sku基本信息
                skuInfoService.save(skuInfoEntity);

                Long skuId = skuInfoEntity.getSkuId();
                // 3.sKu的图片信息 pms_sku_images
                List<SkuImagesEntity> skuImagesEntityList = sku.getImages().stream().map((img) -> {
                    SkuImagesEntity skuImagesEntity = new SkuImagesEntity();
                    BeanUtils.copyProperties(img, skuImagesEntity);
                    skuImagesEntity.setSkuId(skuId);
                    return skuImagesEntity;
                }).filter((item) -> {
                    return StringUtils.isNotEmpty(item.getImgUrl());
                }).collect(Collectors.toList());
                skuImagesService.saveBatch(skuImagesEntityList);

                // 2.sku的属性信息 pms_sku_sale_attr_value
                List<SkuSaleAttrValueEntity> saleAttrValueEntityList = sku.getAttr().stream().map((attr -> {
                    SkuSaleAttrValueEntity skuSaleAttrValueEntity = new SkuSaleAttrValueEntity();
                    BeanUtils.copyProperties(attr, skuSaleAttrValueEntity);
                    skuSaleAttrValueEntity.setSkuId(skuId);
                    return skuSaleAttrValueEntity;
                })).collect(Collectors.toList());
                skuSaleAttrValueService.saveBatch(saleAttrValueEntityList);

                // 4.满减信息 sms_sku_full_reduction ，阶梯价格 sms_sku_ladder ，会员价格 sms_member_price
                SkuFullReductionOthersTo skuFullReductionOthersTo = new SkuFullReductionOthersTo();
                BeanUtils.copyProperties(sku, skuFullReductionOthersTo);
                skuFullReductionOthersTo.setSkuId(skuId);
                if (skuFullReductionOthersTo.getFullCount() != 0 || skuFullReductionOthersTo.getFullPrice().compareTo(new BigDecimal("0")) == 1){
                    couponFeignService.saveSkuInfo(skuFullReductionOthersTo);
                    if (r.getCode() != 0) {
                        log.error("远程调用满减积分服务失败");
                    }
                }

            });

        }
    }

    /**
     * 根据查询条件查询信息
     * @param params
     * @return
     */
    @Override
    public PageUtils queryPageByCondition(Map<String, Object> params) {
        /**
         * status:
         * key:
         * brandId: 0
         * catelogId: 0
        * */
        QueryWrapper<SpuInfoEntity> queryWrapper = new QueryWrapper<>();
        String key = (String) params.get("key");
        if (StringUtils.isNotEmpty(key)){
           queryWrapper.and((w)->{
               w.eq("id",key).or().like("spu_name",key);
           });
        }

        Object status = params.get("status");
        if (status != null){
            queryWrapper.eq("publish_status",status);
        }

        Object brandId =  params.get("brandId");
        if (brandId != null){
            queryWrapper.eq("brand_id",brandId);
        }

        Object catelogId =  params.get("catelogId");
        if (catelogId != null){
            queryWrapper.eq("catalog_id",catelogId);
        }

        IPage<SpuInfoEntity> page = this.page(
                new Query<SpuInfoEntity>().getPage(params),
                queryWrapper
        );

        return new PageUtils(page);
    }

}